<?php if ( ! defined('ABSPATH')) exit('restricted access');

/*
	Plugin Name: WPnukes Gallery
	Plugin URI: http://www.wpnukes.com/plugins/gallery/
	Description: A wpnukes gallery plugin to manage images and videos
	Version: 1.0
	Author: WPnukes
	Author URI: http://www.wpnukes.com/
*/

class wpnukes_gallery
{
	private $baseurl = '';
	private $path = '';
	private $text_domain = 'wpnukes_gallery';
	
	function __construct()
	{
		/** Plugin Base URL */
		$this->baseurl = plugin_dir_url( __FILE__ );

		/** Plugin Path */
		$this->path = plugin_dir_path( __FILE__ );

		/** Language Support */
		load_plugin_textdomain( $this->text_domain, false, $this->path . '/languages/' );
		
		/** Register Post type */
		add_action( 'init', array($this, 'register_posttype'));
		
		/** Custom Taxonomy */
		add_action( 'init', array($this, 'register_taxonomy'), 0 );
		
		/** Contextual Help */
		//add_action( 'contextual_help', array($this, 'contextual_help'), 10, 3 );
		
		/** Load Custom javascript files on new and edit gallery page only */
		add_action( 'admin_print_scripts-post-new.php', array($this, 'admin_script'), 11 );
		add_action( 'admin_print_scripts-post.php', array($this, 'admin_script'), 11 );
		
		/** Load Custom styleshee files */
		add_action( 'admin_print_styles-post-new.php', array($this, 'admin_style'), 11 );
		add_action( 'admin_print_styles-post.php', array($this, 'admin_style'), 11 );

		/** Add Video Callback function */
		//add_action('wp_ajax_add_videos', array($this, 'add_videos'));
		
		/** Ajax Callback */
		add_action('wp_ajax_nukes_gallery', array( $this, 'get_attachments'));
		
		/** Create custom meta box */
		add_action( 'add_meta_boxes', array($this, 'metaboxes') );
		
		/** Filters */
		/*add_filter( 'post_updated_messages', 'updated_messages' );*/
		
		/** Gallery Settings Pages */
		add_action('admin_menu', array($this, 'settings_page'));
		
		/** Save Post */
		add_action( 'publish_wpnukes_galleries', array($this, 'save_post') );
		
		/** Front-end Functionality */
		
		/** Front-end Ajax requests handler */
		add_action('wp_ajax_wpnukes_gallery_ajax_callback', array($this, 'ajax_callback'));
		add_action('wp_ajax_nopriv_wpnukes_gallery_ajax_callback', array($this, 'ajax_callback'));
		
		/** Custom field for gallery categories */
		add_action('wpnukes_gallery_edit_form_fields', array($this, 'category_edit_form'));
		add_action('wpnukes_gallery_add_form_fields', array($this, 'category_edit_form'));
		
		/** Custom field for gallery categories data saving */
		add_action('created_term', array($this, 'save_gallery_thumbnail'));
        add_action('edit_term', array($this, 'save_gallery_thumbnail'));
		
		add_action( 'admin_print_scripts-edit-tags.php', array($this, 'admin_category_script'), 11 );
		//add_action( 'admin_print_scripts-post.php', array($this, 'admin_script'), 11 );
		
		/** Gallery Columns */
		add_filter('manage_edit-wpnukes_galleries_columns', array($this, 'head_only_gallery'), 10);  
		add_action('manage_wpnukes_galleries_posts_custom_column', array($this, 'content_only_gallery'), 10, 2); 
		
		/** Add Shortcode */
		add_shortcode('wpnukes_gallery', array($this, 'wpnukes_gallery_shortcode'));

	}
	
	
	function wpnukes_gallery_shortcode($atts, $content = null)
	{
		extract(shortcode_atts(array('id'=>0,'per_page' => 0,'container'=>'ul'), $atts));
		
		ob_start();
		$this->gallery_html('post_id='.$id.'&images_per_page='.$per_page.'&container='.$container);
		$contents = ob_get_contents();
		ob_end_clean();
		
		return $contents;
	}
	
	function head_only_gallery($default)
	{
		unset($default['date']);
		$default['wpnukes_gallery'] = __('Category');
		$default['gallery_image'] = __('Images and Videos');
		$default['author'] = __('Author');
		$default['date'] = __('Date');
		
		return $default;
	}
	
	function content_only_gallery($column_name, $post_ID)
	{
		if($column_name == 'wpnukes_gallery')
		{
			$terms = get_the_term_list( $post_ID , 'wpnukes_gallery' , '' , ',' , '' );
			if(is_string($terms)) echo $terms;
			else _e('Unable to get category', $this->text_domain);
			
		}elseif($column_name == 'gallery_image')
			echo array_sum( (array)get_post_meta($post_ID, 'wpnukes_gallery_count', true) );
	}

	function settings_page()
	{
    	add_submenu_page('edit.php?post_type=wpnukes_galleries', __('Gallery Settings'), __('Settings'), 'edit_posts', basename(__FILE__), array($this, 'gallery_settings'));
	}
	
	function save_post($post_id)
	{
		global $post;
		if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE) return;
		$post_id = is_int($post_id) ? $post_id : $post->ID;

		$nonce = isset($_POST['wpnukes_gallery_content_nonce']) ? $_POST['wpnukes_gallery_content_nonce'] : '';
		if( ! current_user_can( 'edit_page', $post_id) ) return;
		elseif( ! wp_verify_nonce($nonce, plugin_basename($this->path)) ) return;
		
		$count = array();
		
		/** Store Videos */
		if(isset($_POST['videos']))
		{
			$videos = array_reverse($_POST['videos']);
			$count['videos'] = count($videos);
			update_post_meta($post_id, 'wpnukes_videos', $videos);
		}

		/** Store Gallery */
		if(isset($_POST['gallery']))
		{
			$count['images'] = count($_POST['gallery']);
			update_post_meta($post_id, 'wpnukes_gallery', (array) $_POST['gallery']);
		}
		
		update_post_meta($post_id, 'wpnukes_gallery_count', $count);
	}
	
	function get_attachments()
	{
		if(empty($_POST['ids'])) return;
		$ids = explode(',', $_POST['ids']);

		$attachments = get_posts(array('posts_per_page'=>-1,'post_type'=>'attachment','post__in'=>$ids,'orderby'=>'none'));//print_r($attachments);
		$response = array_flip($ids);

		foreach($attachments as $attachment)
		{
			$thumbnail = current((array)wp_get_attachment_image_src($attachment->ID));
			$response[$attachment->ID] = array('id'=>$attachment->ID,'alt'=>$attachment->post_title,'caption'=>$attachment->post_excerpt,'img'=>$thumbnail);
		}
		
		$response = array_reverse($response);
		exit(json_encode($response));
	}
	
	function gallery_settings()
	{
		$message = '';
		if($_POST) 
		{
			update_option('wpnukes_gallery_settings', $_POST);
			$message = '<div class="updated below-h2" id="message"><p>'.__('Settings are updated.', $this->text_domain).'</p></div>';
		}
		
		/** Load Foruthwave Constructor */	
		$this->_webnukes = &$GLOBALS['_webnukes']; /** Clone the fw_base_class object */
		$this->_webnukes->load('html_class', '', true); /** Load WPnukes HTML class */
		$this->_webnukes->load('wp_html_class','html'); /** Load wordpress HTML class */
		
		$settings = get_option('wpnukes_gallery_settings');
		
		if( empty($this->_webnukes)) wp_die( __('The fourthwave package is required to run this plugin', $this->text_domain) );
				
		//Load default settings
		if(file_exists($this->path . 'config/gallery.php'))
			require_once($this->path . 'config/gallery.php');
		
		
		$data = array();
		foreach($options as $k=>$v)
		{
			$value = (isset($settings[$k])) ? $settings : array($k=>$v['std']);
			$data['fields'][$k] = $this->_webnukes->html->generator($k, $v, $value, 'array');
		}
		
		$content = $this->_webnukes->html->layout('wp_admin/form_table', $data, true);
		$this->_webnukes->html->layout('wp_admin/wrap', array('action'=>'edit.php?post_type=wpnukes_galleries&page=wpnukes-gallery.php','content'=>$content,'nonce_action'=>'general_settings','nonce_name'=>'wpnukes_gallery_settings'));
		echo '<div class="wrap"><div class="icon32 icon32-posts-post" id="icon-edit"><br></div><h2>'.__('Gallery Settings', $this->text_domain).'</h2>'.$message.$this->_webnukes->html->build().'</div>';
		
	}
	
	function metaboxes()
	{
		/** Use metabox on gallery page only */
		if('wpnukes_galleries' != $GLOBALS['post_type']) return;
		
		add_meta_box('the_shortcode', __('Shortcode', $this->text_domain), array($this, 'shortcode'), 'wpnukes_galleries', 'side', 'high');
		
		add_meta_box('the_image_uploader', __('Upload Images', $this->text_domain), array($this, 'upload_images'), 'wpnukes_galleries', 'normal', 'high');
		add_meta_box('the_video_uploader', __('Upload Videos', $this->text_domain), array($this, 'upload_Videos'), 'wpnukes_galleries', 'normal', 'high');
	}
	
	function shortcode()
	{
		echo '[wpnukes_gallery id="'.get_the_ID().'"]';
	}
	
	function upload_images()
	{
		include($this->path.'views/upload_images.php');
	}
	
	/*
	function add_videos()
	{
		if( ! isset($_POST['urls'])) return;
		
		$videos = explode("\n",($_POST['urls']));

		foreach($videos as $k=>$v)
		{
			echo $v.'<br />';
		}
	}*/
	
	function upload_videos()
	{
		include($this->path.'views/upload_videos.php');
	}
	
	function admin_style()
	{
		if('wpnukes_galleries' != $GLOBALS['post_type']) return;
		
		wp_enqueue_style("wp-jquery-ui-dialog");
		wp_enqueue_style( 'gallery-admin-style', $this->baseurl .'css/style.css');
	}
	
	function admin_script()
	{
		if('wpnukes_galleries' != $GLOBALS['post_type']) return;
		
		wp_enqueue_script( 'nukes-videos', $this->baseurl . 'js/jquery-video.js', array('jquery-ui-dialog'));
		wp_enqueue_script( 'galleries-admin-script', $this->baseurl . 'js/image-gallery.js');
	}
	
	/*
	function contextual_help($contextual_help, $screen_id, $screen)
	{
		if('wpnukes_galleries' == $screen->id)
		{
			$contextual_help = '<h2>Gallery</h2>
			<p>Products show the details of the items that we sell on the website. You can see a list of them on this page in reverse chronological order - the latest one we added is first.</p> 
			<p>You can view/edit the details of each product by clicking on its name, or you can perform bulk actions using the dropdown menu and selecting multiple items.</p>';
		}elseif ( 'edit-wpnukes_galleries' == $screen->id )
		{
			$contextual_help = '<h2>Editing Galleries</h2>
			<p>This page allows you to view/modify gallert details. Please make sure to fill out the available boxes with the appropriate details (product image, price, brand) and <strong>not</strong> add these details to the product description.</p>';
		}

		return $contextual_help;
	}

	function updated_messages($messages)
	{
		return 'this is the test message';
	}*/
	
	function register_posttype()
	{
		register_post_type( 'wpnukes_galleries',
        array(
            'labels' => array(
                'name' => _x('Galleries', 'WPnukes Galleries'),
                'singular_name' =>  _x('Gallery', 'WPnukes Gallery'),
                'add_new' =>  _x('Add New', 'gallery'),
                'add_new_item' =>  __('Add New Gallery', $this->text_domain),
                'edit' =>  __('Edit', $this->text_domain),
                'edit_item' =>  __('Edit Gallery', $this->text_domain),
                'new_item' =>  __('New Gallery', $this->text_domain),
                'view' =>  __('View', $this->text_domain),
                'view_item' =>  __('View Gallery', $this->text_domain),
                'search_items' =>  __('Search Gallery', $this->text_domain),
                'not_found' =>  __('No Gallery found', $this->text_domain),
                'not_found_in_trash' =>  __('No Gallery found in Trash', $this->text_domain),
                'parent' =>  __('Parent Gallery', $this->text_domain)
            ),
			'description' => __('Gallery plugin to manage image and videos'),
            'public' => true,
            'menu_position' => 15,
            'supports' => array( 'title', 'thumbnail' ),
            /*'taxonomies' => array( '' ),*/
            'menu_icon' => plugins_url( 'images/gallery-image.png', __FILE__ ),
            'has_archive' => true
        )
	    );
	}
	
	function register_taxonomy()
	{
		register_taxonomy('wpnukes_gallery', 'wpnukes_galleries', array(
			'hierarchical' => true,
			'labels' => array(
				'name' => _x( 'Gallery Categories', 'WPnukes Gallery Categories' ),
				'singular_name' => _x( 'Gallery Category', 'WPnukes Gallery Category' ),
				'search_items' =>  __( 'Search Gallery Categories' ),
				'all_items' => __( 'All Gallery Categories' ),
				'parent_item' => __( 'Parent Gallery' ),
				'parent_item_colon' => __( 'Parent Gallery:' ),
				'edit_item' => __( 'Edit Gallery' ),
				'update_item' => __( 'Update Gallery' ),
				'add_new_item' => __( 'Add New Gallery' ),
				'new_item_name' => __( 'New Gallery Name' ),
				'menu_name' => __( 'Gallery Categories' ),
			),
			'rewrite' => array(
				'slug' => 'galleries', /** This controls the base slug that will display before each term */
				'with_front' => false, /** Don't display the category base before "/galleries/" */
				'hierarchical' => true /** This will allow URL's like "/galleries/videos/youtube/" */
			),
		));
	
		$labels = array(
			'name'              => __( 'Gallery Categories'),
			'singular_name'     => __( 'Gallery Category'),
			'search_items'      => __( 'Search Gallery Categories'),
			'all_items'         => __( 'All Gallery Categories'),
			'parent_item'       => __( 'Parent Gallery Category'),
			'parent_item_colon' => __( 'Parent Gallery Category:'),
			'edit_item'         => __( 'Edit Gallery Category'), 
			'update_item'       => __( 'Update Gallery Category'),
			'add_new_item'      => __( 'Add New Gallery Category'),
			'new_item_name'     => __( 'New Gallery Category'),
			'menu_name'         => __( 'Gallery Categories'),
		);
	}
	
	/**
	 * @see wpnukes_gallery::start_lvl()
	 * @since 1.0.0
	 *
	 * @param array $args Will only append content if style argument value is 'ol' or 'ul'.
	 * @param string $key key of the tag to find from $args array.
	 * @return string opening html tag with relevant class
	 */
	function start_lvl( $args = array(), $key = 'container' ) 
	{
		if(!$args[$key]) return;
		
		$class = $key.'_class';
		$id = isset($args[$key.'_id']) ? ' id="'.$args[$key.'_id'].'"' : '';
		$output = '<div class="'.$args[$class].'"'.$id.'>'."\n";
		switch ( $args[$key] ) {
			case 'div':
				$output = '<div class="'.$args[$class].'"'.$id.'>'."\n";
			break;
			
			case 'ol':
				$output = '<ol class="'.$args[$class].'"'.$id.'>'."\n";
			break;
			default:
			case 'ul':
				$output = '<ul class="'.$args[$class].'"'.$id.'>'."\n";
			break;
			case 'span':
				$output = '<span class="'.$args[$class].'"'.$id.'>'."\n";
			break;
		}
		return $output;
	}
	
	/**
	 * @see wpnukes_gallery::end_lvl()
	 * @since 1.0.0
	 *
	 * @param array $args Will only append content if style argument value is 'ol' or 'ul'.
	 * @param string $key key of the tag to find from $args array.
	 * @return string closing html tag with relevant class
	 */
	function end_lvl( $args, $key = 'container' ) {

		if(!$args[$key]) return;
		
		$output = "</div>\n";
		
		switch ( $args[$key] ) {
			case 'div':
					$output = "</div>\n";
				break;
			case 'ol':
				$output = "</ol>\n";
				break;
			default:
			case 'ul':
				$output = "</ul>\n";
			break;
			case 'span':
				$output = "</span>\n";
			break;
		}
		return $output;
	}
	
	/**
	 * @see wpnukes_gallery::gallery_html()
	 * @since 1.0.0
	 *
	 * @param array $args Will only append content if style argument value is 'ol' or 'ul'.
	 * @return string returns complete HTML of the current gallery post according to the provided arguments.
	 */
	function gallery_html($args = array())
	{
		global $post;
		$default = array('container' => 'div', 'container_id'=>'wpnukes_gallery', 'container_class' => 'gallery', 'image_container' => 'div', 'image_container_class'=>'image %s', 'detail_container' =>'',
						'detail_class' => '', 'title_limit' => false, 'content_limit' => 200, 'show_views' => true, 'thumb_size' => 'thumbnail', 'data_id' =>'id-%d', 
						'data_type' => '%s_filter', 'child_class' => 'gal_li', 'callback' => false, 'show_featured' => false, 'images_per_page' => 12, 'offset' => 0, 
						'post_id' => null );

		$args = wp_parse_args($args, $default);
		
		/** replace the %s within the foreach loop */
		$image_container_class =  $args['image_container_class'];?>
        
        <?php echo $this->start_lvl($args); ?>
        
        <?php $post_id = ($args['post_id']) ? $args['post_id'] : get_the_ID(); 
		$data = $this->gallery_array($post_id, $args['thumb_size'], $args);
		if($args['images_per_page']) $data = array_slice($data, $args['offset'], $args['images_per_page']); //printr($data); ?>
        
        <?php /** If User want to use the callback function instead of using default output */
		if($args['callback'])  return call_user_func($args['callback'], $data, $args); ?>

		<?php if($data): foreach($data as $k=>$v): ?>
        	
			<?php /** If the main container is div then the child tag is according to the parent */
			if($args['container'] != 'div'): ?>
            	<li class="<?php echo $args['child_class']; ?>" data-id="<?php printf($args['data_id'], $k); ?>" data-type="<?php printf($args['data_type'], $v['type']); ?>">
            <?php else: ?>
            	<div class="<?php echo $args['child_class']; ?>" data-id="<?php printf($args['data_id'], $k); ?>" data-type="<?php printf($args['data_type'], $v['type']); ?>">
            <?php endif; ?>
            	
				<?php $gr_type = ($v['type'] == 'video') ? 'vid' : 'pic'; ?> 
					<div class="gal_img">
                        <a href="<?php echo $v['url']; ?>" id="<?php echo $post->ID.'_'.$v['uid']; ?>" class="fancybox-media" data-fancybox-group="<?php echo $gr_type; ?>-gallery" title="<?php echo $this->get_title($v['title'], ''); ?>">
                           
                           <?php $args['image_container_class'] =  sprintf($image_container_class, $gr_type); ?>
                            
                            <?php echo $this->start_lvl($args, 'image_container'); /** Start image container */ ?>
                                <img src="<?php echo $v['thumb']; ?>" alt="<?php echo $this->get_title($v['title'], $args['title_limit']); ?>" /> 
                                <span class="pic_info">
                                    <span class="bar"> 
                                        <?php if($args['show_views']): ?>
                                            <span class="views"><?php echo __('Views').' '. number_format($v['views']); ?></span> 
                                        <?php endif; ?>
                                        <?php if($v['type'] == 'video'): ?>
                                            <span class="duration"><?php echo strftime('%H:%M:%S', $v['duration']); ?></span> 
                                        <?php endif; ?>
                                    </span>
                                    <span class="img"></span>
                                </span> 
                                
                            <?php echo $this->end_lvl($args, 'image_container'); /** End Image Container */?>
                        </a>
                        <div class="short_details">
                            <h4><a href="<?php echo get_permalink(); ?>"><?php echo $this->get_title($v['title'], $args['title_limit']); ?></a></h4>
                            <span><?php _e('By'); ?>: <em><?php echo $v['author']; ?></em></span><span><?php echo __('on').' '.$v['date']; ?></span> 
                        </div><!-- short_details ends -->
					</div><!-- gal_img ends -->   
                <div class="pic_details">
                    <h4><a href="<?php echo get_permalink($post->ID); ?>"><?php echo $this->get_title($v['title']); ?></a></h4>
                    <span class="gener"><?php _e('Category'); ?>: <?php echo $v['cat']; ?></span>
                    <p><?php echo ( $args['content_limit'] ) ? character_limiter(strip_tags($v['desc']), $args['content_limit']) : $v['desc']; ?></p>
                </div><!-- Pic Details end -->
                
                <div class="pic_stats">
                    <ul>
                        <?php if($args['show_views']): ?>
                        <li><a href="javascript:void(0);" class="view_icon"><?php _e('Views', $this->text_domain); ?> : <?php echo number_format($v['views']); ?></a></li>
                        <?php endif; ?>
                        <li><a href="javascript:void(0);" class="user_icon"><em><?php echo $v['author']; ?></em></a></li>
                        <li><a href="javascript:void(0);" class="date_icon"><?php echo $v['date']; ?></a></li>
                    </ul>
                </div>
                <!-- pic_stats end --> 
                
            <?php if($args['container'] != 'div'): ?> </li>
            <?php else: ?> </div>
            <?php endif; ?>
        <?php endforeach; endif; ?>
        	
		<?php echo $this->end_lvl($args);
	}
	
	/**
	 * @see wpnukes_gallery::gallery_array()
	 * @since 1.0.0
	 *
	 * @param int $post_id Id of the gallery post.
	 * @param string $thumb_size Either register size of the image or an array of width height.
	 * @return array returns the array of images and videos found in the current gallery post.
	 */
	public function gallery_array($post_id, $thumb_size, $args = array())
	{
		global $post, $wpdb, $wp_embed;

		$title_limit = 25;
		
		/** Default values of the 3rd argument $args */
		$default = array('show_featured' => false, 'number' => -1, 'mime_type' => 'all', 'no_detail' => false);
		$args = wp_parse_args($args, $default);

		$is_featured = ($args['show_featured']) ? true : false;
		
		$views = get_post_meta($post_id, 'wpnukes_gallery_views_counter', true);
		
		$content = array();
		
		$showposts = $args['number'];
		
		/** Check whether only featured images need to show */
		if($is_featured) {
			$gallery = (get_post_thumbnail_id(get_the_ID())) ? array(get_post_thumbnail_id(get_the_ID())) : array();
			$gallery = ($gallery) ? $gallery : array(current( (array)get_post_meta($post_id, 'wpnukes_gallery', true)));
		}else{
			$gallery = get_post_meta($post_id, 'wpnukes_gallery', true);
		}

		if( $gallery && ($args['mime_type'] == 'all' || $args['mime_type'] == 'image') )
		{

			$gallery = ( $showposts == 1 ) ? current((array)$gallery) : $gallery;
			$posts = get_posts(array('showposts' => $showposts,'post_type'=>'attachment', 'post_mime_type'  => '"image/jpeg,image/gif,image/jpg,image/png"', 
								'include'=>$gallery));

			$gallery = array_flip((array)$gallery);

			if($posts)
			{
				foreach($posts as $p)
				{
					$img_info = array();
					$thumb = wp_get_attachment_image_src($p->ID, $thumb_size);
					if($args['no_detail']) $img_info['thumb'] = $thumb[0];
					else{
						
						$url = wp_get_attachment_url($p->ID);
						$img_info['type'] = 'picture';
						$img_info['uid'] = $p->ID;
						$img_info['url'] = $url;
						$img_info['thumb'] = $thumb[0];
						$img_info['title'] = $p->post_title;
						$img_info['date'] = date(get_option('date_format'), strtotime($p->post_date));
						$img_info['author'] = get_userdata($p->post_author)->display_name;
						$img_info['views'] = isset($views[$p->ID]) ? $views[$p->ID] : 0;
						$img_info['duration'] = '';
						$img_info['cat'] = get_the_term_list(get_the_ID(), 'wpnukes_gallery', '', ' ,');
						$img_info['desc'] = $p->post_excerpt;
					}
					$gallery[$p->ID] = $img_info;
					
					
				}
			}
		}
		$content = $gallery;

		/** Check whether only featured videos need to show */
		$videos = get_post_meta($post_id, 'wpnukes_videos', true);

		if($videos && ($args['mime_type'] == 'all' || $args['mime_type'] == 'video') )
		{
			
			foreach(array_reverse((array)$videos) as $video)
			{
	
				$img_info = array();
				if($args['no_detail']) $img_info['thumb'] = $video['thumb'];
				else{
					$url = ($video['source'] == 'vimeo') ? 'http://vimeo.com/'.$video['id'] : 'http://www.youtube.com/watch?v='.$video['id'];
					$img_info['type'] = 'video';
					$img_info['uid'] = $video['id'];
					$img_info['url'] = $url;
					$img_info['thumb'] = $video['thumb'];
					$img_info['title'] = $video['title'];
					$img_info['date'] = get_the_date();
					$img_info['author'] = $video['author'];
					$views[$video['id']] = isset($views[$video['id']]) ? $views[$video['id']] : 0;
					$img_info['views'] = (int)$video['views'] + $views[$video['id']];
					$img_info['duration'] = $video['duration'];
					$img_info['cat'] = $video['tags'];
					$img_info['desc'] = character_limiter($video['desc'], 100);
				}
				
				if($is_featured){
					 if(isset($video['featured']) && $video['featured']) $content[] = $img_info;
				}else{
					$content[] = $img_info;
				}				
			}
		}
		return $content;
	}
	
	/**
	 * @see wpnukes_gallery::get_title()
	 * @since 1.0.0
	 *
	 * @return string returns formatted title.
	 */
	function get_title($title, $limit = '')
	{
		return ( $limit ) ? substr(str_replace(array('-', '_', '+'), ' ', $title), 0, $limit) : str_replace(array('-', '_'), ' ', $title);
	}
	
	
	
	/**
	 * @see wpnukes_gallery::category_edit_form_fields()
	 * @since 1.0.0
	 *
	 * @param obj $term An object of the current term
	 * @return string prints the html of custom fields.
	 */
	function category_edit_form($term)
	{
		$term = (object) $term;
		$term->term_id = isset($term->term_id) ? $term->term_id : '';
		$image = get_option('wpnukes_gallery_category_image_'.$term->term_id);
		require_once($this->path . 'views/category_form.php');
	}
	
	/**
	 * @see wpnukes_gallery::save_gallery_thumbnail()
	 * @since 1.0.0
	 *
	 * @param int $term_id Term id of the current saved term.
	 * @return bolean Returns true if values successfullly saved.
	 */
	function save_gallery_thumbnail($term_id)
	{
		if( ! isset($_POST['taxonomy']) || 'wpnukes_gallery' != $_POST['taxonomy']) return;
		
		if(isset($_POST['catpic'])) update_option('wpnukes_gallery_category_image_'.$term_id, $_POST['catpic']);
		else update_option('wpnukes_gallery_category_image_'.$term_id, '');
		return true;
	}
	
	/**
	 * @see wpnukes_gallery::admin_category_script()
	 * @since 1.0.0
	 *
	 * @return string Callback of the admin enqueue scripts to enqueue custom styles and scripts.
	 */
	 
	function admin_category_script()
	{
		if('wpnukes_galleries' != $GLOBALS['post_type']) return;
		/** Load Style */
        wp_enqueue_style('thickbox');
		
        /** Load Scripts */
        wp_enqueue_script(array('thickbox', 'media-upload', 'quicktags'));
	}
	
	/**
	 * @see wpnukes_gallery::get_terms()
	 * @since 1.0.0
	 *
	 * @param string $thumb_size Thumbsize to fetch the images of specific size.
	 * @return array returns an array of terms image and posts images in a specific term.
	 */
	function get_terms($thumb_size = 'thumbnail')
	{
		$terms = get_terms('wpnukes_gallery');
		$return = array();
		foreach($terms as $term)
		{
			$term_image = get_option('wpnukes_gallery_category_image_'.$term->term_id);
			$posts = get_posts(array('posts_per_page'=>3, 'post_type'=>'wpnukes_galleries', 'wpnukes_gallery'=>$term->slug));
			$att = array();
			
			foreach($posts as $p)
			{
				if(has_post_thumbnail($p->ID))
				{
					$att[] = array('thumb'=>current((array)wp_get_attachment_image_src( get_post_thumbnail_id($p->ID), $thumb_size )));
				}else{
					$att[] = current((array)$this->gallery_array($p->ID, $thumb_size, array('number'=>1, 'mime_type'=>'image', 'no_detail' => true)));
				}
			}
			$return[] = array('id'=>$term->term_id, 'name'=>$term->name, 'link'=>get_term_link($term), 'term_image'=>$term_image, 'images' => $att);
		}
		
		return $return;
	}
	
	/**
	 * @see wpnukes_gallery::gallery_albums()
	 * @since 1.0.0
	 *
	 * @param string $thumb_size Thumbsize to fetch the images of specific size.
	 * @return string returns complete HTML of the current gallery album according to the provided arguments.
	 */
	function gallery_albums($thumbsize = 'thumbnail', $exclude = null)
	{
		$galleries = $this->get_terms($thumbsize);
		if($galleries):?>
        
			<ul class="galleries">
				<?php foreach($galleries as $k=>$v): ?>
                    <li> 
                        <a href="<?php echo $v['link']; ?>"><img src="<?php echo $v['term_image']; ?>" alt="<?php echo $v['name']; ?>" /></a>
                        <div class="categorypics">
                            <?php foreach($v['images'] as $img): ?>
                                <img src="<?php echo $img['thumb']; ?>" alt="" />
                            <?php endforeach; ?>
                        </div>
                    </li>
                <?php endforeach;?>
			</ul>
            
        <?php endif;
	}
	
	/** Front End functions */
	
	/**
	 * @see wpnukes_gallery::ajax_callback()
	 * @since 1.0.0
	 *
	 * @return string print the sccuess message if the views counter is updated successfully.
	 */
	 
	function ajax_callback()
	{
		if( ! isset($_POST['subaction'])) wp_die();
		
		$action = $_POST['subaction'];
		
		if($action == 'views_counter')
		{
			if( ! isset($_POST['uid']) ) wp_die( __('Invalid Post UID', $this->text_domain) );
			
			$uid = explode('_', $_POST['uid']);
			if( ! is_numeric($uid[0]) || ! is_numeric($uid[1])) wp_die( __('Invalid Post UID', $this->text_domain) );
			
			$views = (array) get_post_meta($uid[0], 'wpnukes_gallery_views_counter', true);
			
			if(is_array($views)) $views[$uid[1]] = $views[$uid[1]] + 1;
			else $views[$uid[1]] = 1;

			update_post_meta($uid[0], 'wpnukes_gallery_views_counter', $views);
		}
		
		wp_die();
	}
}

/** Initiate the Class */
$wpnukes = new wpnukes_gallery;